<?php
class DB{
	private static $_db;
	private static $_connect;
	public function __construct($config=null)
	{
		$host = "127.0.0.1";
		$user = "root";
		$passwd = "";
		$database = "yqingdisplay";
		if($config!=null){
			$host = $config['host'];
			$user = $config['user'];
			$passwd = $config['password'];
			$database = $config['database'];
		}
		self::$_connect = new mysqli($host,$user,$passwd,$database);
		if (self::$_connect->connect_errno) {
		    echo "Failed to connect to MySQL: (" . self::$_connect->connect_errno . ") " . self::$_connect->connect_error;
		    die;
		}
		self::$_connect->query("set names utf8;");
	}

	public function status(){
		return "ok";
	}

	public function close()
	{
		self::$_connect->close();
		self::$_db = null;
		self::$_connect = null;
	}
	public static function get_instance($config=null)
	{
		if(self::$_db===null){
			self::$_db = new DB($config);
		}
		return self::$_db;
	}

	public function query($sql)
	{
		// echo $sql;die;
		if($result=self::$_connect->query($sql)){
			return $result;
		} else {
			self::$_db->close();
			return false;
		}
	}
	/*
	 * @param string $sql  sql语句
	 * @param bool $one    返回单条数据或者数据数组
	 * @return array
	 */
	public function select($sql,$one = false)
	{
		$result = $this->query($sql);
		$rows = [];
		while($row = $result->fetch_array(MYSQLI_ASSOC)){
				$rows[] = $row;
		}
		$result->free();
		if($one && count($rows)>0){
			return array_shift($rows);
		}
		return $rows;
	}
	public function escape($value)
	{
		return self::$_connect->real_escape_string($value);
	}
	/*
	 * @param string $tablename  表名称
	 * @param array $attributes  字段=>值 数组
	 * @return bool
	 */
	public function insert($tablename,$attributes=[])
	{
		if(empty($attributes)) return false;
		$sql = "insert ignore into `$tablename` set ";
		$content = null;
		foreach($attributes as $k=>$v){
			$v_str = null;
			if ( is_numeric($v) )
				$v_str = "'{$v}'";
			else if ( is_null($v) )
				$v_str = 'NULL';
			else
				$v_str = "'" . $this->escape($v) . "'";

			$content .= "`$k`=$v_str,";
		}
		$sql.=trim($content,',');
		// var_dump($sql);die;
		return $this->query($sql);
	}
	/*
	 * @param string $tablename  表名称
	 * @param array $attributes  需要更新的 字段=>值 数组
	 * @param array|string $condition   条件限制
	 * @return bool
	 */
	public function update($tablename,$condition=[],$attributes=[])
	{
		if ( null==$tablename || empty($attributes))
			return false;

		$sql = "UPDATE `$tablename` SET ";
		$content = null;

		foreach ( $attributes as $k => $v )
		{
			$v_str = null;
			if ( is_numeric($v) )
				$v_str = "'{$v}'";
			else if ( is_null($v) )
				$v_str = 'NULL';
			else
				$v_str = "'" . $this->escape($v) . "'";

			$content .= "`$k`=$v_str,";
		}

		$content = trim($content, ',');
		$sql .= $content;
		if(!empty($condition)){
			$sql.=" where ".$this->_buildCondition($condition);
		}

		return $this->query($sql);
	}
	private function _buildCondition($condition,$logic="and")
	{
		if(is_string($condition)){
			return $condition;
		} elseif(is_array($condition)){
			$constring = '';
			foreach ($condition as $key => $value) {
				$constring.="$logic `$key`='".$this->escape($value)."' ";
			}
			return trim($constring,$logic);
		}

	}
	/*
	 * @param string $tablename  表名称
	 * @param array|string $condition   条件限制
	 * @return bool
	 */
	public function delete($tablename,$condition)
	{
		if(empty($tablename) || empty($condition)){
			return false;
		}
		$sql = "delete from `$tablename` where ".$this->_buildCondition($condition);
		return $this->query($sql);
	}

}
//var_dump(DB::get_instance()->delete('test',['id'=>34]));

